const mongoose=require('mongoose');
const Cat=require('../models/cat.model');

// post
exports.create = function(req, res, next) {
    const cat = new Cat(req.body);
    cat.save().then(data => {
      res.json(data);
    });
  };
  // update
exports.update = function(req, res, next) {
    const id = req.params.id; // req.query req.body req.params
  
    Cat.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
      res.json(data); // 特别强调，在更新阶段，这个data是上一次没有更新完成的数据，而不是已经更新完成的数据
    });
  };

  
// delete
exports.delete = function(req, res, next) {
    const id = req.params.id; // req.query req.body req.params
  
    Cat.findByIdAndRemove(id, function(err, doc) {
      res.json({ status: 200, message: '数据删除成功' });
    });
  };

  
  exports.list = function(req, res, next) {
    const page = req.body.page ? req.body.page : 1;
    const rows = req.body.rows ? req.body.rows : 5;
    const queryCondition = {};
  
    if (req.body.name && req.body.name.trim().length > 0) {
      queryCondition = {
        name: new RegExp(name, 'i')
      };
    }
  
    Cat.paginate(queryCondition, { page: +page, limit: +rows }, function(
      err,
      result
    ) {
      result.rows = result.docs;
      delete result.docs;
      res.json(result);
    });
  };